package com.jingmi.jingmiliving.commodity.controller;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.jingmi.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;


@RestController
@Slf4j
public class TestBucketController {
    @Resource
    private OSSClient ossClient;
    @RequestMapping("/test")
    public R TestUpload() throws FileNotFoundException {
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        //用户进行 API 访问或日常运维，请登录 RAM 控制台创建 RAM 用户。
        String accessKeyId = "LTAI5t7kLGDubARfLXaFZ9e2";
        String accessKeySecret = "7Q8UQJ1M17FAQJfsbOVTbCfqsTAP45";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "jingmi-living-10000";
        String objectName = "512.png";
        String filePath = "C:\\Users\\27713\\Pictures\\512.png";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
    @RequestMapping("/test2")
    public R testUpload2() throws FileNotFoundException {
        InputStream inputStream = new FileInputStream("C:\\Users\\27713\\Pictures\\512 (3).png");
        ossClient.putObject("jingmi-living-10000","512 (3).png",inputStream);
        ossClient.shutdown();
        return null;
    }
}
